package com.hzsai.socket;

import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * hzsai 2019/11/6
 * usage: 创建启动服务类
 **/
@Component
@Order(1)
public class SocketIOServerRunner implements CommandLineRunner {

    private final SocketIOServer server;

    private static final Logger logger = LoggerFactory.getLogger(SocketIOServerRunner.class);

    // SocketIO添加namespace之外，还需要给namespace添加
    /**
     * 构造注入
     * @param server
     */
    @Autowired
    SocketIOServerRunner(SocketIOServer server) {
        this.server = server;
    }

    /**
     * Callback used to run the bean.
     * 启动socketServer
     *
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    @Override
    public void run(String... args) throws Exception {

        logger.debug("****************************");
        logger.debug("*                          *");
        logger.debug("*                          *");
        logger.debug("* SocketIOServer启动中...   *");
        logger.debug("*                          *");
        logger.debug("*                          *");
        server.start();
        logger.debug("* SocketIOServer启动成功    *");
        logger.debug("****************************");
    }

    @PreDestroy
    public void preDestroy() {
        server.stop();
    }
}
